<?php
	define ('RRDS', '/var/rrd/');
	define ('CACHE', 'png-cache');
	define ('CACHE_TIMEOUT', 59);

	$Buf = '';
	$Status = 0;
	$Cmd = '/usr/bin/rrdtool graph';

	$Options = '';
	if (! array_key_exists ('json', $_GET) or NULL === ($JSON = json_decode ($_GET ['json'], TRUE))) die (); // error decoding JSON
	if (! array_key_exists ('Defs', $JSON) or ! array_key_exists ('Plot', $JSON)) die (); // without these there's no graph to plot
	if (array_key_exists ('Colours', $JSON)) foreach ($JSON ['Colours'] as $Name => $Value) {
		$Options .= ' --color '.$Name.'#'.$Value;
	}
	if (array_key_exists ('Fonts', $JSON)) foreach ($JSON ['Fonts'] as $Name => $Value) {
		$Options .= ' --font '.$Name.':'.$Value;
	}
	if (array_key_exists ('Options', $JSON)) foreach ($JSON ['Options'] as $Name => $Value) {
		$Options .= ' --'.str_replace ('_', '-', $Name);
		(is_string ($Value) or is_numeric ($Value)) and $Options .= ' "'.$Value.'"';
	}
	foreach ($JSON ['Defs'] as $Name => $Value) {
		$Options .= ' DEF:'.$Name.'="'.RRDS.$Value ['rrd'].'.rrd":'.$Value ['field'].':'.$Value ['CF'];
	}
	if (array_key_exists ('VDefs', $JSON)) foreach ($JSON ['VDefs'] as $Name => $Value) {
		$Options .= ' VDEF:'.$Name.'='.$Value;
	}
	if (array_key_exists ('CDefs', $JSON)) foreach ($JSON ['CDefs'] as $Name => $Value) {
		$Options .= ' CDEF:'.$Name.'='.$Value;
	}
	foreach ($JSON ['Plot'] as $Name => $Value) {
		if (array_key_exists ('Enabled', $Value) and FALSE === $Value ['Enabled']) continue;
		switch ($Value ['type']) {
			case 'GPRINT': $Options .= ' '.$Value ['type'].':'.$Name.':"'.$Value ['text'].'"'; break;
			case 'COMMENT': $Options .= ' '.$Value ['type'].':"'.$Value ['text'].'"'; break;
			default:
				$Options .= ' '.$Value ['type'].':'.$Name.'#'.$Value ['colour'];
				array_key_exists ('name', $Value) and $Options .= ':"'.$Value ['name'].'"';
		}
	}
	$Options = trim ($Options);

	if (array_key_exists ('Cache', $JSON) and array_key_exists ('alt', $_GET) and strlen ($_GET ['alt'])) {
		file_exists (CACHE) or mkdir (CACHE);
		$Picture = CACHE.'/'.$_GET ['alt'].'.png';
		if (! file_exists ($Picture) or (time () - filemtime ($Picture) > CACHE_TIMEOUT)) {
			exec ("$Cmd $Picture $Options", $Status, $Buf);
		}
		header ("Location: $Picture");
	} else {
		ob_start ();
			passthru ("$Cmd - --imgformat PNG $Options" , $Status);
			$Status === 0 and $Buf = ob_get_contents ();
		ob_end_clean ();
		header ('Content-type: image/png');
		echo ($Buf);
	}
?>